import fetch from '../utils/fetch';
import { message } from 'antd';
import config from '../config';
import { ADMIN_ADD, ADMIN_ALL, ADMIN_EDIT } from '../actionTypes';

export const updateEdit = (payload) => ({
  type: ADMIN_EDIT,
  payload,
});

export const updateAll = (payload) => ({
  type: ADMIN_ALL,
  payload,
});

export const updateAdd = (payload) => ({
  type: ADMIN_ADD,
  payload,
});

export const getAll = () => async (dispatch, getState) => {
  const { all } = getState().admin;
  if (all.length !== 0) {
    return false;
  }

  const res = await fetch({
    url: `${config.HOST}/admin/lesson/all`
  });
  dispatch(updateAll(res.data));
};

export const deleteLesson = (id) => async (dispatch, getState) => {
  if (!/^\d+$/g.test(id)) {
    message.success('没有课程Id');
    return false;
  }
  const del = await fetch({
    method: 'post',
    url: `${config.HOST}/admin/lesson/del`,
    param: {
      id,
    },
  });

  if (del.code === 200) {
    let all = [...getState().admin.all];
    const index = all.findIndex(item => item.id === id);
    all.splice(index, 1);
    dispatch(updateAll(all));
    message.success('删除成功');
  } else {
    message.error('删除失败');
  }
};
